import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import moment from 'moment';
import lscache from 'lscache';
import router from 'umi/router';


import {
  Row,
  Col,
  Icon,
  Card,
  Form,
  Modal,
  InputNumber,
  Input,
  Select,
  Button,
  Divider,
  Avatar,
  Radio,
  DatePicker,
  Pagination,
} from 'antd';
const { RangePicker } = DatePicker;
import StandardTable from '@/components/StandardTable1';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from '@/pages/List/TableList.less';
import { object } from 'prop-types';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@Form.create()

/* eslint react/no-multi-comp:0 */
@connect(({ user, page, order,createOrder, getRoom,checkinorder, loading }) => ({
  currentUser: user.currentUser,
  page,
  createOrder,
  getRoom,
  order,
  checkinorder,
  loading: loading.models.page,
  currentUserLoading: loading.effects['user/fetchCurrent'],
  projectLoading: loading.effects['project/fetchNotice'],
  activitiesLoading: loading.effects['activities/fetchListList'],
}))
class Workplace extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      expandForm: false,
      selectedRows: [],
      getRoomData: [],
      formValues: {},
      OrderStatus: '',
      monthRoomPrice: [],
      current: 1,
      pageSize: 10,
      visible: false,
      disStatus: true,
      sRoomId: '',
      makeType: false // 根据型号不同更改显示
    };
    this.columns = [
      {
        title: '订单号',
        dataIndex: 'orderNo',
      },
      {
        title: '用户姓名',
        dataIndex: 'name',
      },
      {
        title: '联系方式',
        dataIndex: 'phone',
      },
      {
        title: '预订房型',
        dataIndex: 'room.name',
        render: val => `${val} `,
  
      },
      {
        title: '下单时间',
        dataIndex: 'orderTime',
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
        needTotal: true,
      },
      {
        title: '入住时间',
  
        render: (text, val) => <span>{moment(val.checkInTime).format('YYYY-MM-DD')}~{moment(val.checkOutTime).format('YYYY-MM-DD')}</span>,
      },
      {
        title: '订单状态',
  
        dataIndex: 'orderStatus',
        // eslint-disable-next-line no-nested-ternary
        render: val => <span>{val === 0 ? "待确认" : (val === 5 ? "待支付" : (val === 15 ? "已付款" : (val === 20 ? "待入住" : (val === 30 ? "已入住" : (val === 40 ? "已完成" : "已取消")))))}</span>,
  
      },
      {
        title: '预订方式',
  
        dataIndex: 'wxOpenId',
        // eslint-disable-next-line no-nested-ternary
        render: val => <span>{val === '后台预订' ? "后台预订" : "小程序预订"}</span>,
  
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <Link to={`/dashboard/orderdetails/${record.id}`} className="啊啊啊啊啊啊啊啊">详情</Link>
            <Divider type="vertical" />
            <Button 
              type="primary"
              disabled={record.isConfirm}
              htmlType="submit"
              onClick={() => this.handleUpdateModalVisible(true, record)}
            >
              确认
            </Button>
  
            <Divider type="vertical" />
  
            <Button 
              type="primary" 
              disabled={record.isConfirm === false || record.orderStatus === 30 || record.orderStatus === 40 || record.orderStatus === 100 ?  true : false }
              htmlType="submit"
              onClick={() => this.handleUpdatecheckIn(true, record)}
            >
              入住
            </Button>
          </Fragment>
        ),
      },
    ];
  }

  componentDidMount() {
    const { current, pageSize } = this.state;
    const { userInfo } = this.props;
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
    var widowflag = true;
    for (var v = 0; v < Agents.length; v++) {
      if (userAgentInfo.indexOf(Agents[v]) > 0) {
        widowflag = false;
        break;
      }
    }
    if (widowflag) {
      this.setState({
        widowflag: { display: "block" },
        widowflags: { display: "none" }
      })

    } else {
      this.setState({
        widowflag: { display: "none" },
        widowflags: { display: "block" }
      })
    }
    this.state.userInfo = lscache.get('userInfo')
    if (this.state.userInfo) {
    } else {
      router.push("/user")
    }
    const { dispatch, form } = this.props;
    const { OrderStatus } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        OrderStatus,
        skipCount: (current-1)*pageSize,
        maxResultCount: pageSize,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'page/page1',
        payload: values,
      });
    });
    const values = {
      skipCount: 0,
      maxResultCount: 100,
    };
    dispatch({
      type: 'getRoom/getRoom1',
      payload: values,
      callback: response => {
        if (response.success === true) {
          this.state.getRoomData = response.result.items
        }
      }
    });

  } 
 
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues, OrderStatus } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    const params = { 
      skipCount: (pagination.current-1) * pagination.pageSize,
      maxResultCount: pagination.pageSize,
    };
    if (sorter.field) {
      let sorters = `${sorter.order}`
      if (sorters === 'ascend') {
        sorters = 'orderTime'
      } else if (sorters === 'descend') {
        sorters = 'orderTime\ndesc'
      } else {
        sorters = ''
      }
      params.Sorting = sorters;
    }


    dispatch({
      type: 'page/page1',
      payload: {
        ...params,
        OrderStatus,
      }
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    console.log('handleSearch')
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { OrderStatus } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        OrderStatus,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'page/page1',
        payload: values,
      });
    });
  };

  handleUpdatecheckIn = (flag, record) => {
    const { dispatch, form } = this.props;
    const { OrderStatus } = this.state;
    const params = {
      id: record.id,
    };
    dispatch({
      type: 'checkinorder/checkinorder1',
      payload: params,
      callback: response => {
        form.validateFields((err, fieldsValue) => {
          if (err) return;
          const values = {
            ...fieldsValue,
            OrderStatus,
            updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
          };
          this.setState({
            formValues: values,
          });
          dispatch({
            type: 'page/page1',
            payload: values,
          });
        });
      }
    });
  }

  handleUpdateModalVisible = (flag, record) => {
    const { dispatch, form } = this.props;
    const { OrderStatus } = this.state;
    const params = {
      id: record.id,
    };
    dispatch({
      type: 'order/order1',
      payload: params,
      callback: response => {
        form.validateFields((err, fieldsValue) => {
          if (err) return;
          const values = {
            ...fieldsValue,
            OrderStatus,
            updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
          };
          this.setState({
            formValues: values,
          });
          dispatch({
            type: 'page/page1',
            payload: values,
          });
        });
      }
    });

  };

  handleSearch1 = e => {
    this.setState({
      current:1
    })
    console.log('handleSearch1')
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
        OrderStatus: e.target.value,
      });
      dispatch({
        type: 'page/page1',
        payload: {
          ...values,
          OrderStatus: e.target.value,
        },
      });
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator, getFieldValue },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="搜索条件">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">订单号</Option>
                  <Option value="1">姓名</Option>
                  <Option value="2">手机号码</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          {
            getFieldValue('status') === '0' ? (
              <Col md={8} sm={24}>
                <FormItem label="">
                  {getFieldDecorator('OrderNo')(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
            ) : null
          }
          {
            getFieldValue('status') === '1' ? (
              <Col md={8} sm={24}>
                <FormItem label="">
                  {getFieldDecorator('Name')(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
            ) : null
          }
          {
            getFieldValue('status') === '2' ? (
              <Col md={8} sm={24}>
                <FormItem label="">
                  {getFieldDecorator('Phone')(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
            ) : null
          }
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );

  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, form } = this.props;
    const { OrderStatus } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        skipCount: (current-1)*pageSize,
        maxResultCount: pageSize,
        ...fieldsValue,
        OrderStatus,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'page/page1',
        payload: values,
      });
    });

  }
  // 点击新建订单的按钮
  handleCreateOrdle = () => {
    this.setState({
      visible: true
    });
  }
  //新建订单创建按钮点击
  handleOk = () => {
    const { dispatch } = this.props;
    const root = this;
    var phones = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]|19[0-9]|16[0-9])[0-9]{8}$/;
    var re = /^[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?$/;
    if(root.createRoomid){
    if (root.createName) {
       if (root.createPhone) {
          if (re.test(root.createEmail)) {
            let createOrders ={
              avatarUrl:'',
              checkInTime:this.createInDate,
              checkOutTime:this.createOutDate,
              email:this.createEmail,
              name:this.createName,
              nickName:this.createWxname,
              phone:this.createPhone,
              roomId:this.createRoomid,
              wxOpenId:'后台预订',
              isSystemOrder:1
            }
            dispatch({
              type: 'createOrder/createOrder1',
              payload: createOrders,
              callback: response => {
                if (response.success === true) {
            root.setState({
              visible: false
            });
            dispatch({
              type: 'page/page1',
            });
                }
              }
            });
          } else {
             alert('您的邮箱输入有误！')
          }
       } else {
          alert('您的手机号码输入有误！')
       }
    } else {
       alert('您的姓名不可为空！')
    }
  }else{
    alert('请选择您要居住哪个房间！')
  }


  }
  //新建订单取消按钮点击
  handleCancel = () => {
    this.setState({
      visible: false,
      disStatus: true,
    });
  }
  //获取新建订单入住日期
 onChangeRangePicker = (date, dateString)=> {
  this.createInDate = dateString[0];
  this.createOutDate = dateString[1];
}

onOpenChange = (status) => {
  const { dispatch } = this.props;
  const { sRoomId, monthRoomPrice } = this.state;
  if (status && sRoomId) {
    dispatch({
      type: 'room/GetRoomPrice',
      payload: {
        Roomid: this.state.sRoomId,
        From: moment().format('YYYY-MM-DD'),
        End: moment().add('month', 12).format('YYYY-MM-DD')
      },
      callback: res => {
        if (res.success === true) {
          const data = res.result.months;
          const arr = [];
          Object.values(data).map(item => {
            item.map(value => {
              arr.push(value.date.substring(0, 10))
            })
          })
          this.setState({
            monthRoomPrice: arr
          })
        }
      }
    })
  }
}

disabledDate = (current) => {
  const fliterCurrent = !this.state.monthRoomPrice.includes(current.format('YYYY-MM-DD'))
  return current < moment().subtract('day', 1) || current >moment().add('month', 12) || fliterCurrent;
}

dateRender = (current) => {
  const style = {};
  if (!this.state.monthRoomPrice.includes(current.format('YYYY-MM-DD'))) {
    style.background = '#f0f0f0';
  }
  return (
    <div className="ant-calendar-date" style={style}>
      {current.date()}
    </div>
  );
}

//是否支持包院
handleSelectChangeisPrivateRoom = (value) =>{
this.createisPrivateRoom = value
}
//获取新建订单房间ID
handleSelectChange = (value) =>{
  this.createRoomid = value
  this.setState({
    sRoomId: value,
    disStatus: false,
  })
}
//获取新建订单email
onChangeEmail(e){
  this.createEmail = e.target.value
}
//获取新建订单姓名
onChangeName(e){
  this.createName = e.target.value
}
//获取新建订单微信姓名
onChangeWxName (e){
  this.createWxname = e.target.value
}
//获取新建订单手机号码
onChangePhone (e){
  this.createPhone = e.target.value
 
}

render() {
  const { visible, 
    createInDate,
    createOutDate,
    createWxOpeid,
    createEmail,
    createName,
    createPhone,
    createWxname,
    createRoomid,
    createisPrivateRoom,
  } = this.state;
  const {
    dataAll,
    currentUser,
    currentUserLoading,
    page: { data },
    loading,
  } = this.props;
  for (let i = 0; i < data.items.length; i++) {
    if (!data.items[i].isConfirm && data.items[i].orderStatus === 15) {
      data.items[i].flag = ""
    } else {
      data.items[i].flag = "disabled"
    }
    if (data.items[i].orderStatus === 20) {
      data.items[i].flags = ""
    } else {
      data.items[i].flags = "disabled"

    }
  }
  const { selectedRows, OrderStatus } = this.state;

  const pageHeaderContent =
    currentUser && Object.keys(currentUser).length ? (
      <div className={styles.pageHeaderContent}>
        <div className={styles.avatar}>
          <Avatar size="large" src={currentUser.avatar} />
        </div>
        <div className={styles.content}>
          <div className={styles.contentTitle}>
            您好，
            {currentUser.name}
            ，祝你开心每一天！
          </div>
        </div>
      </div>
    ) : null;
    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
        content={pageHeaderContent}
      >

        <Card bordered={false}>
          <Button type="dashed" onClick={this.handleCreateOrdle}>
            <Icon type="plus" /> 
            新建订单
          </Button>
          <Divider style={{ marginBottom: 32 }} />
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Radio.Group buttonStyle="solid" value={OrderStatus} onChange={this.handleSearch1}>
                <Radio.Button className={styles.rbut} value="">全部</Radio.Button>
                <Radio.Button className={styles.rbut} value="0">待确认</Radio.Button>
                <Radio.Button className={styles.rbut} value="5">待支付</Radio.Button>
                <Radio.Button className={styles.rbut} value="20">待入住</Radio.Button>
                <Radio.Button className={styles.rbut} value="30">已入住</Radio.Button>
                <Radio.Button className={styles.rbut} value="40">已完成</Radio.Button>
                <Radio.Button className={styles.rbut} value="100">已取消</Radio.Button>
              </Radio.Group>
            </div>
            <Fragment >
              <StandardTable
                style={this.state.widowflag}
                selectedRows={selectedRows}
                data={data}
                columns={this.columns}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            </Fragment>
            <div style={this.state.widowflags}>
              {data.items.length === 0 ? "" :
                data.items.map((item) => {
                  return (
                    <div key={item.id}>
                      <Card style={{ width: 356, marginBottom: 10 }}
                        actions={[
                          <Button type="primary" disabled={item.flag} onClick={() => this.handleUpdateModalVisible(true, item)}>确认</Button>,
                          <Button type="primary" disabled={item.flags} onClick={() => this.handleUpdatecheckIn(true, item)}>入住</Button>,
                          <Button ><Link to={`/dashboard/orderdetails/${item.id}`}>详情</Link></Button>
                        ]}>
                        <p>订单号:{item.orderNo}</p>
                        <p>用户姓名:{item.name}</p>
                        <p>联系方式:{item.phone}</p>
                        <p>预订房型:{item.room.name}</p>
                        <p>预订时间:{moment(item.orderTime).format('YYYY-MM-DD')}</p>
                        <p>入住时段:{moment(item.checkInTime).format('YYYY-MM-DD')}~{moment(item.checkOutTime).format('YYYY-MM-DD')}</p>
                        <p>订单状态:{item.orderStatus === 0 ? "待确认" : (item.orderStatus === 5 ? "待支付" : (item.orderStatus === 15 ? "已付款" : (item.orderStatus === 20 ? "待入住" : (item.orderStatus === 30 ? "已入住" : (item.orderStatus === 40 ? "已完成" : "已取消")))))}</p>
                        <p>预订方式:{item.wxOpenId==='后台预订'?'后台预订':'小程序预订'}</p>
                      </Card>
                    </div>
                  )
                })
              }
              <Pagination
                showSizeChanger
                // onChange={this.onShowSizeChange}
                onChange={this.onShowSizeChange}
                defaultCurrent={this.state.current?this.state.current:1}
                current={this.state.current?this.state.current:1}
                pageSize={10}
                total={500}
              />
            </div>
          </div>
        </Card>
        <Modal
          title={<div style={{ textAlign: 'center' }}>新建订单</div>}
          visible={visible}
          width={500}
          centered
          closable={false}
          footer={null}
          destroyOnClose
          maskClosable={false}
        >
        {/* <p>
          是否包院：
          <Select placeholder="请选择"  style={{ width: '70%' }} defaultValue={this.state.createisPrivateRoom} onChange={this.handleSelectChangeisPrivateRoom}>
                  <Option value="0">不包院</Option>
                  <Option value="1">包院</Option>
                </Select>
        </p> */}
          <p>入住房间：
            <Select placeholder="请选择房间"  style={{ width: '70%' }} defaultValue={this.state.createRoomid} onChange={this.handleSelectChange}>
              {
                this.state.getRoomData.map(item => (
                  item.roomStatus === 0 ? <Option key={item.id} value={item.id}>{item.name}</Option> : null
                ))
              }
            </Select>
          </p>
          <p>入住日期：
            <RangePicker 
              onOpenChange = {this.onOpenChange}
              onChange={this.onChangeRangePicker}
              disabledDate={this.disabledDate}
              // dateRender={this.dateRender} //更改样式
              style={{ width: '70%' }} 
              disabled={this.state.disStatus}
            />
          </p>
          <p>您的邮箱：<Input onChange={this.onChangeEmail.bind(this)} defaultValue={this.state.createEmail} style={{ width: '70%' }} /></p>
          <p>您的名字：<Input onChange={this.onChangeName.bind(this)} defaultValue={this.state.createName} style={{ width: '70%' }} /></p>
          <p>微信名称：<Input onChange={this.onChangeWxName.bind(this)} defaultValue={this.state.createWxname} style={{ width: '70%' }} /></p>
          <p>手机号码：<Input onChange={this.onChangePhone.bind(this)} defaultValue={this.state.createPhone} style={{ width: '70%' }} /></p>
          <div style={{ textAlign: 'center' }}>
            <Button onClick={this.handleOk} icon='check' style={{ marginRight: 32 }}>新建</Button>
            <Button onClick={this.handleCancel}>取消</Button>
          </div>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default Workplace;
